package com.yxb.cms.service;


import com.yxb.cms.architect.constant.BusinessConstants;
import com.yxb.cms.architect.constant.BussinessCode;
import com.yxb.cms.architect.utils.BussinessMsgUtil;
import com.yxb.cms.architect.utils.DbIdUtil;
import com.yxb.cms.dao.DbServerManagerMapper;
import com.yxb.cms.domain.dto.BussinessMsg;
import com.yxb.cms.domain.vo.DbServerManager;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 云资源管理服务
 * @author YXB
 */
@Service
@Log4j2
public class ServerManagerService {


    @Autowired
    private DbServerManagerMapper serverManagerMapper;



    /**
     * 云资源信息分页展示列表
     *
     * @return
     */
    public Map<String, Object> selectServerListByPage(DbServerManager serverManager) {

        Map<String, Object> map = new HashMap<>();
        try {

            List<DbServerManager> serverManagerList = serverManagerMapper.selectServerManagerListByPage(serverManager);
            Long count = serverManagerMapper.selectServerManagerCount(serverManager);

            map.put("code", 200);
            map.put("msg", "获取信息成功");
            map.put("count", count);
            map.put("data", serverManagerList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            map.put("code", 500);
            map.put("msg", "资源信息查询异常");
        }
        return map;
    }


    /**
     * 保存修改云资源信息
     * @return
     */
    public BussinessMsg saveOrUpdateServerManager(DbServerManager serverManager, String userId) {
        log.info("保存云资源信息");
        long start = System.currentTimeMillis();
        try {

            //保存云资源信息
            if(StringUtils.isEmpty(serverManager.getServerId())){

                serverManager.setServerId(DbIdUtil.generate());

                serverManager.setServerStatus(BusinessConstants.SERVER_STATUS_1.getCode());
                serverManager.setCreaterUserId(userId);
                serverManager.setCreaterTime(new Date());
                serverManagerMapper.insertSelective(serverManager);

            }else{

                serverManager.setModifierTime(new Date());
                serverManager.setModifierUserId(userId);
                serverManagerMapper.updateByPrimaryKeySelective(serverManager);
            }
        } catch (Exception e) {
            log.error("保存云资源信息内部错误{}", e.getMessage(), e);
            throw e;
        } finally {
            log.info("保存云资源信息结束,用时" + (System.currentTimeMillis() - start) + "毫秒");
        }
        return BussinessMsgUtil.returnCodeMessage(BussinessCode.GLOBAL_SUCCESS);

    }
}
